/*
	网络请求和全局常用变量
*/
import Vue from 'vue'
import link from './link.js'
import cache from './cache.js'
import user from './user.js'
import message from './message.js'
// 全局请求路径，也就是后端的请求基准路径
let BASE_URL = 'https://www.qiuh.top:6952/api/'
// let BASE_URL = 'https://www.heyue-tech.com/api/'
// let BASE_URL = 'https://www.xiaoshi.net.cn/api/'
//let WSS_URL = 'wss://www.heyue-tech.com/'

// let BASE_URL = 'https://3518g67a99.goho.co/api' // 内网穿透域名
// let BASE_URL = 'http://41ce42c2.vaiwan.com/' // 内网穿透域名
// let BASE_URL = 'http://101.132.254.109:10026/'



BASE_URL = setBaseUrl(BASE_URL) //在设置页面动态设置后端地址
let WSS_URL = setWssURL(BASE_URL)
// cache.removeStorage('BaseUrl')

//是否使用mock
// const BASE_URL = 'https://www.heyue-tech.com/vote/' 
let limit = 10;//一页显示10条数据
let imgUrl = BASE_URL + 'common/file/preview/' //图片请求地址
let video = BASE_URL + 'common/file/download/' //
let file = BASE_URL + 'common/file/preview/'

// http://localhost:8001/api/common/file/preview/
/*
	url:路径
	params:参数 类型:对象
	loading:是否显示加载中  类型:布尔 
	默认不显示加载中
*/
export default {
	limit,
	imgUrl,
	BASE_URL,
	WSS_URL,
	file,
	video,
	async httpGet(url,params,loading){
		 loading = loading || false
		 return await Http(url,params,'GET',loading)
	},
	async httpGetJson(url,params,loading){
		loading = loading || false
		return await Http(url,params,'GET',loading,'application/json')
	},
	async httpPost(url,params,loading){
		loading = loading || false
		return await Http(url,params,'POST',loading)
	},
	async httpPostJson(url,params,loading){
		loading = loading || false
		return await Http(url,params,'POST',loading,'application/json')
	},
	async httpMultipart(url,params,loading){
		loading = loading || false
		return await Http(url,params,'POST',loading)
	}
	
	
}
function Http(url,params,method,loading,contentType = 'application/x-www-form-urlencoded;charset=utf-8'){
	let token = user.getUser('userData').token || null
	needLogin(url,token) //是否需要登录
	let header
	if(token){
		if(method == 'POST'){
			header = {
				'token':token,
				'content-type': contentType
			}
		}else{
			header = {
				'token':token
			}
		}
	}else{
		if(method == 'POST'){
			header = {
				'content-type': contentType
			}
		}
	}
	
	
	let loadings = loading
	if(loadings){
		uni.showLoading({
			title: "加载中",
		    mask: true,
		});
	}
	
	return new Promise((resolve,reject)=>{
		// console.log('地址',BASE_URL)
		uni.request({
			url:BASE_URL+url,
			method: method,
			data: params,
			header:header,
			success: (res)=>{
				
				//判断后台token是否过期
				backTokenExpire(res)
				if(!res.data.success){
					// message.showToast(res.data.msg)
				}
				resolve(res.data)
			},
			fail: (err)=>{
				reject(err)
			},
			// 完成之后关闭加载效果
			complete:()=>{
			    //  关闭正在等待的图标
			    uni.hideLoading(); 
			}
		})
	})
}
/**
	是否需要登录
	url:接口路径
	token:token
*/
function needLogin(url,token){
	// 不需要登录的url
	console.log('needLogin_url:',url)
	let notNeedLoginUrl = ['vote/mobile/user/login',
						   'vote/mobile/user/sendCaptcha'
					]
			
	// let dynamicLoginUrls = ['resolution/mobile/detail']
	// let dynamicLoginUrl = dynamicLoginUrls[0]
	// var result=patt.test(str);
	// console.log('匹配的url:',notNeedLoginUrl.indexOf(url))
	if(notNeedLoginUrl.indexOf(url) == -1){
			if(token == null){
				link.goAndClose(
					'/common/components/login/login'
				)
			}
			//是否超时
			// else if(tokenExpire(24*60)){
			// 	link.goAndClose('/common/components/login/mobile-login')
			// 	message.showToast('登录已过期')
			// }
	}
	
}

/**
	判断token是否超时
	time:超时时间（分钟）
*/
function tokenExpire(time){
	time = time * 60 *1000
	//获取当前时间和上一次登录完成的时间
	let currentData = Date.now()
	let loginTime = user.getUser('userData').loginTime
	let timeInterval = currentData - loginTime
	//是否超时
	if(timeInterval > time){
		return true
		console.log('token过期了,token已经存在的时间=',timeInterval);
	}else{
		return false
	}
	
}

/**
	判断后台token是否过期
	过期转到登录页面
*/
function backTokenExpire(res){
	//tonken 过期
	//if(['Unauthorized','token is invalid, please log in again','token失效，请重新登录','未授权'].includes(res.data.msg)){
	if(res.data.code == 401){
		link.goTo('/common/pages/login/login')
		setTimeout(()=>{
			message.showToast('请先登录')
		},100)
	}
}



function setBaseUrl(url){
	console.log("setBaseUrl_begin");
	let BaseUrl = cache.getStorage('BaseUrl')
	if(BaseUrl){
		return BaseUrl
	}else{
		return url
	}
	
}
//设置直播地址
function setWssURL(url){
	let newUrl = ''
	let prefix = url.slice(0,5)
	if(prefix == 'https'){
		newUrl = url.replace('https://', '')
		var index = newUrl.indexOf("\/");
		newUrl = newUrl.substring(0,index+1);
		return 'wss://'+newUrl
	}else{
		newUrl = url.replace('http://', '')
		var index = newUrl.indexOf("\/");
		newUrl = newUrl.substring(0,index+1);
		return 'ws://'+newUrl
	}
	
}